﻿using System;
using System.Net;

namespace NetWork.Layer
{
	public class HttpUtil 
	{
		private Uri uri = null;
		private string serverUrl = null;
		private WebClient webClient = new ShortWebClient();
		//用以排除延迟导致的重复收包问题，即发一包只能收一包，多余收到的包无效，丢弃
		private bool m_bNeedReceive = false;
		private HTTPManager _http;
		
        public string ServerUrl
        {
            get { return serverUrl; }
            set {
                serverUrl = value;
                uri = new Uri(serverUrl);
				if (!IsIpAddress (serverUrl)) {
					return;
				}
				//当不支持ipv4且当前地址是ipv4时，将ipv4转成DNS64和NAT64支持的ipv6
				UnityEngine.Debug.Log("Ipv4 is supported " + YCPlugin.IsSupportIpv4(uri.Host));

				if (!YCPlugin.IsSupportIpv4(uri.Host) && uri.HostNameType == UriHostNameType.IPv4)
				{
				    var split = uri.Host.Split('.');
				    var ipv4 = new int[4];
				    for (int i = 0; i < 4; i++)
				    {
				        ipv4[i] = int.Parse(split[i]);
				    }

                    string ipv4Ip = "";
                    for (int i = 0; i < 4; i++)
                    {
                        ipv4Ip += ipv4[i].ToString();
                        if (i != 3)
                        {
                            ipv4Ip += ".";
                        }
                    }

                    string ipv6 = string.Format("http://[{0}]:{1}{2}", YCPlugin.GetIpv6(ipv4Ip), uri.Port, uri.AbsolutePath);
                    UnityEngine.Debug.Log("http Server ip convert to ipv6 : " + ipv6);
                    /*
				    string ipv6 = string.Format("http://[64:ff9b::{0}{1}:{2}{3}]:{4}{5}",
				        Convert.ToString(ipv4[0], 16),
				        Convert.ToString(ipv4[1], 16),
				        Convert.ToString(ipv4[2], 16),
				        Convert.ToString(ipv4[3], 16),
				        uri.Port,
				        uri.AbsolutePath
				        );
                    */            
				    var uri2 = new Uri(ipv6);
				    serverUrl = ipv6;
				    uri = uri2;
				}
            }
        }
		
		public HttpUtil(string serverUrl, HTTPManager kHTTP)
        {
			ServerUrl = serverUrl;
			_http = kHTTP;
            webClient.UploadDataCompleted += UpdataCompleted;
        }
		
		public bool Send(byte[] data)
        {
            if(webClient.IsBusy)
            {
                return false;
            }
            try
            {
				//webClient.Headers.Set();
                webClient.UploadDataAsync(uri, data);
				m_bNeedReceive = true;
                return true;
            }
            catch (WebException we)
            {
                UnityEngine.Debug.Log("Send: "+we);
                return false;
            }
        }
		
		public void UpdataCompleted(Object sender, UploadDataCompletedEventArgs args)
        {
            if (args.Error == null)
            {
                if (args.Result != null && args.Result.Length > 0)
                {
					if (m_bNeedReceive)
					{
						m_bNeedReceive = false;
						_http.SessionCompleted(true, args.Result);
					}
					return;
                }
                else
                {
                    _http.SessionCompleted(false, null);
                    UnityEngine.Debug.LogError("UpdataCompleted error: return empty");
                }
            } else {
				_http.SessionCompleted(false, null);
				UnityEngine.Debug.LogError("UpdataCompleted error: "+args.Error);
            }

			return;
        }

		private bool IsIpAddress(string address)
		{
			var ca = address.ToCharArray ();
			int count = 0;
			foreach (var c in ca) {
				if (c == '.') {
					++count;
				}
			}
			return count >= 3;
		}
	}
}